// packageE/appointment/store/AppointmentAddGood/AppointmentAddGood.js 
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    keyword: "",
    radio: "",
    active: "1",
    getJson: {},
    getDatUrl: "",
    title: "",
    categoryMenus: [],
    addCategoryIndex: "",
    projectArray: [],
    showSearchProject: false,
    showSearchProject_index: null,
    goodsCategory: [],
    goods: {
      title: "",
      category: [],
      sku: "",
      stock: "",
      thumb: "",
      thumb_url: [],
      content: "",
      market_price: [],
      price: "",
      cost_price: "",
      no_refund: false,
      goods_sn: "",
      product_sn: "",
      reduce_stock_method: 0
    },
    widgets: {
      appointment_project: []
    },
    goodsId: null,
    page: 1,
    projectList: [],
    total_page: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (!this.options.id) {
      wx.setNavigationBarTitle({
        title: '商品发布',
      })
    } else {
      wx.setNavigationBarTitle({
        title: '商品编辑',
      })
      this.setData({
        // goodsId:this.options.id
      })
      this.getGoodsDetail();
    }
    this.getProject();
    this.getClass();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  async getGoodsDetail() {
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("plugin.appointment.frontend.project-goods.goods-detail"),
      data: {
        goods_id: this.options.id
      },
    });
    if (data.result == 1) {
      console.log(data)
      let {
        category,
        title,
        sku,
        stock,
        thumb,
        thumb_url,
        content,
        market_price,
        price,
        cost_price,
        no_refund,
        goods_sn,
        product_sn,
        reduce_stock_method
      } = data.data;
      this.setData({
        'goods.category': category,
        'goods.title': title,
        'goods.sku': sku,
        'goods.stock': stock,
        'goods.thumb': thumb,
        'goods.thumb_url': thumb_url,
        'goods.content': content,
        'goods.market_price': market_price,
        'goods.price': price,
        'goods.cost_price': cost_price,
        'goods.no_refund': no_refund,
        'goods.goods_sn': goods_sn,
        'goods.product_sn': product_sn,
        'goods.reduce_stock_method': reduce_stock_method,
        'widgets.appointment_project': data.data.has_many_appointment_goods
      })
      this.reversefilterCategory(category);
    } else {
      app.tips(data.msg);
    }
  },
  reversefilterCategory(array) {
    let arr = [];
    for (let i = 0; i < array.length; i++) {
      arr[i] = {};
      for (let j = 0; j < array[i].length; j++) {
        if (array[i][j].level == 1) {
          arr[i].parentid = array[i][j].id;
          arr[i].parent_name = array[i][j].name;
        } else if (array[i][j].level == 2) {
          arr[i].childid = array[i][j].id;
          arr[i].child_name = array[i][j].name;
        } else if (array[i].length == 3 && array[i][j].level == 3) {
          arr[i].thirdid = array[i][j].id;
          arr[i].third_name = array[i][j].name;
        }
      }
    }
    // this.goodsCategory = arr;
    this.setData({
      goodsCategory: arr
    })
    console.log(arr, "wwwwwwwwwwwwwww");
  },
  async submitTap() {
    console.log(this.data.goods, 'goods')
    console.log(this.data.widgets.appointment_project, 'widgets.appointment_project')
    let is_validate = await this.validate();
    if (!is_validate) return;
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("plugin.appointment.frontend.project-goods.add-goods"),
      data: is_validate,
    });
    if (!data.result) {
      app.tips(data.msg);
      return
    }
    app.tips(data.msg);
    wx.navigateBack({
      delta: 1
    })
  },
  validate() {
    if (app._isTextEmpty(this.data.goods.title)) {
      app.tips('请输入商品名称');
      return false
    }
    if (app._isTextEmpty(this.data.goods.sku)) {
      app.tips('请输入商品单位');
      return false
    }
    if (this.data.goods.category.length <= 0) {
      app.tips('请选择商品分类');
      return false
    }
    if (app._isTextEmpty(this.data.goods.thumb)) {
      app.tips('请上传商品图片');
      return false
    }
    if (app._isTextEmpty(this.data.goods.price)) {
      app.tips('请输入商品现价');
      return false
    }
    if (app._isTextEmpty(this.data.goods.stock)) {
      app.tips('请输入商品库存');
      return false
    }
    let projectArr = this.data.widgets.appointment_project;
    let projectCheck = 4;
    if (projectArr.length <= 0) projectCheck = 1;
    for (let i = 0; i < projectArr.length; i++) {
      if (app._isTextEmpty(projectArr[i].project_id)) {
        projectCheck = 2;
      } else if (app._isTextEmpty(projectArr[i].service_count)) {
        projectCheck = 3;
      }
    }
    if (projectCheck == 1) {
      app.tips("请添加项目信息");
      return false;
    } else if (projectCheck == 2) {
      app.tips("请选择项目");
      return false;
    } else if (projectCheck == 3) {
      app.tips(`请填写预约次数`);
      return false;
    }
    let json = {
      goods: {
        ...this.data.goods
      },
      widgets: {
        ...this.data.widgets
      }
    };
    if (this.data.goodsId) {
      json.id = this.data.goodsId;
    }
    console.log(json)
    return json
  },
  getProjectInit() {
    this.setData({
      page: 1,
      total_page: 0
    })
  },
  onClickLeft() {
    this.setData({
      showSearchProject: false,
      page: 1,
      total_page: 0,
      showSearchProject_index: null,
      radio: ""
    })
  },
  radioGroup(e) {
    console.log(e)
    this.setData({
      radio: e.detail
    })
  },
  projectCheck(item, projectList) {
    var str = "请选择";
    if (projectList.length <= 0) return str;
    if (item.project_id) {
      for (var i = 0; i < projectList.length; i++) {
        if (projectList[i].id == item.project_id) {
          str = projectList[i].title;
        }
      }
    }
    return str;
  },
  onClickRight() {
    this.setData({
      showSearchProject: false,
      ['widgets.appointment_project[' + this.data.showSearchProject_index + '].project_id']: this.data.radio
    })
    // this.selectComponent('.classCell' + this.data.showSearchProject_index).setData({
    //   linkConten: this.projectCheck(this.data.widgets.appointment_project[this.data.showSearchProject_index], this.data.projectList)
    // })
  },
  tapTouch(e) {
    let {
      id
    } = e.currentTarget.dataset.item;
    if (this.data.radio && this.data.radio == id) {
      return
    } else {
      this.setData({
        radio: id
      })
    }
  },
  async getProject() {
    let json = {
      search: {},
      page: this.data.page
    }
    json.search.title = this.data.keyword ? this.data.keyword : "";
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("plugin.appointment.frontend.project.store-project-list"),
      data: json,
    });
    if (!data.result) {
      app.tips(data.msg)
      return
    }
    this.setData({
      projectList: data.data.data,
      total_page: data.data.last_page
    })
  },
  removeCategory(e) {
    let {
      index
    } = e.currentTarget.dataset;
    this.data.goodsCategory.splice(index, 1);
    this.data.goods.category.splice(index, 1);
    this.setData({
      goodsCategory: this.data.goodsCategory,
      'goods.category': this.data.goods.category
    })
    console.log(this.data.goodsCategory, this.data.goods.category)
  },
  async on_search(e) {
    this.setData({
      keyword: e.detail
    })
    this.getProjectInit();
    await this.getProject();
  },
  async showSearchProjectOpen(e) {
    let ind = e.currentTarget.dataset.key;
    this.setData({
      radio: this.data.widgets.appointment_project[ind].project_id
    })
    this.getProjectInit();
    await this.getProject();
    this.setData({
      showSearchProject: true,
      showSearchProject_index: ind
    })
  },
  addProjectMethod() {
    let obj = {
      service_count: "", //预约次数
      project_id: "", //选择的项目id
      price: "",
      worker_commission: "",
      merchant_staff_commission: "",
      area_set: 0,
      province: "",
      city: "",
      district: "",
      street: ""
    };
    // let arr = [];
    // this.widgets.appointment_project.push(obj);
    this.data.widgets.appointment_project.push(obj)
    this.setData({
      'widgets.appointment_project': this.data.widgets.appointment_project
    })
  },
  tabChange(e) {
    console.log(e)
    this.setData({
      active: e.detail.name
    })
  },
  switchTap_area(e) {
    let {
      index
    } = e.currentTarget.dataset;
    this.setData({
      ['widgets.appointment_project[' + index + '].area_set']: e.detail ? 1 : 0
    })
  },
  switchTap(e) {
    this.setData({
      "goods.no_refund": !this.data.goods.no_refund
    })
  },
  editStockType(evt) {
    this.setData({
      'goods.reduce_stock_method': evt.detail
    });
  },
  showStockTypePop() {
    this.selectComponent('.stock-type-pop').showPopup();
  },
  saveGoodsDetail(e) {
    this.setData({
      'goods.content': e.detail
    })
  },
  showGoodsDetailPop() {
    this.selectComponent('.goods-details-pop').showPopup();
  },
  inpM(e) {
    let {
      inpval,
      index
    } = e.currentTarget.dataset;
    if (this.data.active == '1') {
      this.setData({
        ['goods.' + inpval]: e.detail
      })
    } else {
      console.log(e)
      this.setData({
        ['widgets.appointment_project[' + index + '].' + inpval]: e.detail
      })
      console.log(this.data.widgets.appointment_project[index][inpval])
    }
  },
  imgUpload(e) {
    let url = e.detail;
    let key = e.currentTarget.dataset.key;
    if (key == 'thumb_url') {
      this.data.goods.thumb_url.push(url)
      console.log(this.data.goods, 'sssssssssssssss')
      this.setData({
        'goods.thumb_url': this.data.goods.thumb_url
      })
      return
    }
    this.setData({
      ['goods.' + key]: url
    })
  },
  editCategory(evt) {
    let {
      manyGoodsCategory
    } = evt.detail;
    let goodsCategory = this.data.goodsCategory;
    let isRepeat = goodsCategory.some((item) => {
      if (manyGoodsCategory.thirdid) {
        return (item.parentid == manyGoodsCategory.parentid) && (item.childid == manyGoodsCategory.childid) && (item.thirdid == manyGoodsCategory.thirdid);
      } else {
        return (item.parentid == manyGoodsCategory.parentid) && (item.childid == manyGoodsCategory.childid);
      }
    });
    if (isRepeat) return app.tips("不能重复添加商品分类");
    goodsCategory.push(manyGoodsCategory);
    this.setData({
      goodsCategory
    });
    this.data.goodsCategory.forEach((ele, index) => {
      this.filterCategory(ele, index)
    })
  },
  filterCategory(obj, ind) {
    let isObj = {};
    let arr = [];
    for (const key in obj) {
      if (key == "parentid") {
        isObj = {};
        isObj.id = obj[key];
        isObj.level = 1;
        arr[0] = isObj;
      } else if (key == "childid") {
        isObj = {};
        isObj.id = obj[key];
        isObj.level = 2;
        arr[1] = isObj;
      } else if (key == "thirdid") {
        isObj = {};
        isObj.id = obj[key];
        isObj.level = 3;
        arr[2] = isObj;
      }
    }
    this.data.goods.category[ind] = arr;
  },
  async getClass() {
    let {
      data
    } = await app._getNetWork({
      url: app.getNetAddresss("plugin.appointment.frontend.project-goods.get-category-list"),
      data: {
        id: this.options.id
      },
    });
    if (data.result == 1) {
      this.setData({
        categoryMenus: data.data
      })
    } else {
      app.tips(data.msg)
    }
  },
})